﻿using AiBLSmartEdu.Module.AIMentalHealthSelfAssessment.API.DTOs;
using AutoMapper;
using DocumentFormat.OpenXml.Office.SpreadSheetML.Y2023.MsForms;
using Domain.Entities;
using Domain.Entities.MentalHealth;
using FluentMigrator.Runner.Generators;
using FrameworkCore.DI;
using FrameworkCore.Events;
using FrameworkCore.Extensions;
using FrameworkCore.Helpers;
using FrameworkCore.Interfaces;
using FrameworkCore.Models;
using FrameworkCore.Repositories;
using OllamaSharp;
using OllamaSharp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace AiBLSmartEdu.Module.AIMentalHealthSelfAssessment.API.Services;

/// <summary>
/// 心理测试服务
/// </summary>
public class PsychologicalTestService : IScopedDependency
{
    private readonly IOllamaApiClient _ollama;
    private readonly IRepository<MentalHealthSelfAssessment> _mentalHealthSelfAssessmentRepository;
    private readonly ICurrentUserService _currentUserService;
    private readonly IMapper _mapper;

    public PsychologicalTestService(IOllamaApiClient ollama,
        IRepository<MentalHealthSelfAssessment> mentalHealthSelfAssessmentRepository,
        ICurrentUserService currentUserService,
        IMapper mapper)
    {
        _ollama = ollama;
        _mentalHealthSelfAssessmentRepository = mentalHealthSelfAssessmentRepository;
        _currentUserService = currentUserService;
        _mapper = mapper;
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="filter">分页输入模型</param>
    /// <returns></returns>
    public async Task<PageResult<MentalHealthSelfAssessmentOutputModel>> PageAsync(MentalHealthSelfAssessmentPaginationFilter filter)
    {
        return (await _mentalHealthSelfAssessmentRepository.GetOrderedQueryable(query =>
        {
            return query.OrderByDescending(o => o.Id)
            //.Where(x=>x.CreatedBy== _currentUserService.UserId)
            .WhereIf(!string.IsNullOrWhiteSpace(filter.Keyword), x => x.PsychologicalDescription.Contains(filter.Keyword));

        }, filter).ProjectToPaginatedDataAsync<MentalHealthSelfAssessment, MentalHealthSelfAssessmentOutputModel>(
            filter.PageNumber,
            filter.PageSize,
            _mapper.ConfigurationProvider
        )).ToPageList();
    }

    public async Task<PsychologicalQuestions> GenerateQuestionsAsync(PsychologicalTestRequest request, CancellationToken cancellationToken = default)
    {
        var prompt = $@"你是一名心理测试医生，根据以下用户描述的心理健康状况，生成一份心理测试问卷。必须严格遵守以下要求：
1. 生成一个包含15个问题（不可少于此数）的问卷
2. 每个问题都应有5个选项，例如：1分表示“完全不符合”，5分表示“完全符合”
3. 问题要针对性地评估用户描述中可能存在的心理健康问题
4. 输出格式必须是JSON数组，只包含问题对象数组部分
5. 确保所有问题都是独特的、不重复的

用户描述：{request.UserDescription}

重要要求：
- 必须生成至少15个问题（最低15个）
- 不要包含任何说明文字或额外信息
- 只输出JSON数组格式的数据

请仿照下面的模板生成JSON数组格式的问卷内容：
[
    {{
        ""id"": 1,
        ""question"": ""问题文本"",
        ""options"": [
            {{""value"": 1, ""label"": ""选项1""}},
            {{""value"": 2, ""label"": ""选项2""}},
            {{""value"": 3, ""label"": ""选项3""}},
            {{""value"": 4, ""label"": ""选项4""}},
            {{""value"": 5, ""label"": ""选项5""}}
        ],
        ""score"": 5
    }},更多测试题......，
    {{
        ""id"": 2,
        ""question"": ""问题文本"",
        ""options"": [
            {{""value"": 1, ""label"": ""选项1""}},
            {{""value"": 2, ""label"": ""选项2""}},
            {{""value"": 3, ""label"": ""选项3""}},
            {{""value"": 4, ""label"": ""选项4""}},
            {{""value"": 5, ""label"": ""选项5""}}
        ],
        ""score"": 5
    }},
    {{
        ""id"": 3,
        ""question"": ""问题文本"",
        ""options"": [
            {{""value"": 1, ""label"": ""选项1""}},
            {{""value"": 2, ""label"": ""选项2""}},
            {{""value"": 3, ""label"": ""选项3""}},
            {{""value"": 4, ""label"": ""选项4""}},
            {{""value"": 5, ""label"": ""选项5""}}
        ],
        ""score"": 5
    }},更多测试题......，
{{
        ""id"": 14,
        ""question"": ""问题文本"",
        ""options"": [
            {{""value"": 1, ""label"": ""选项1""}},
            {{""value"": 2, ""label"": ""选项2""}},
            {{""value"": 3, ""label"": ""选项3""}},
            {{""value"": 4, ""label"": ""选项4""}},
            {{""value"": 5, ""label"": ""选项5""}}
        ],
        ""score"": 5
    }},更多测试题......，
    {{
        ""id"": 15,
        ""question"": ""问题文本"",
        ""options"": [
            {{""value"": 1, ""label"": ""选项1""}},
            {{""value"": 2, ""label"": ""选项2""}},
            {{""value"": 3, ""label"": ""选项3""}},
            {{""value"": 4, ""label"": ""选项4""}},
            {{""value"": 5, ""label"": ""选项5""}}
        ],
        ""score"": 5
    }}
]
";

        var generateRequest = new GenerateRequest()
        {
            Model = "qwen:14b",
            Format = "json",
            Prompt = prompt
        };

        //var responseBuilder = new StringBuilder();
        //await foreach (var response in _ollama.GenerateAsync(generateRequest, cancellationToken))
        //{
        //    if (response?.Response != null)
        //    {
        //        responseBuilder.Append(response.Response);
        //    }
        //}

        // 去除最外层的花括号（如果有的话）
        //var jsonResponse = responseBuilder.ToString();
        //if (jsonResponse.StartsWith("{") && jsonResponse.EndsWith("}"))
        //{
        //    jsonResponse = jsonResponse.TrimStart('{').TrimEnd('}');
        //}
        var jsonResponse = @"[
    {
        ""id"": 1,
        ""question"": ""你最近是否经常感到情绪低落或悲伤？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 2,
        ""question"": ""你是否对曾经喜欢的事情失去了兴趣？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 3,
        ""question"": ""你是否经常感到疲倦或缺乏精力？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 4,
        ""question"": ""你是否对自己的未来感到绝望或无助？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 5,
        ""question"": ""你是否感到难以集中注意力或做出决定？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 6,
        ""question"": ""你是否经常感到焦虑或紧张？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 7,
        ""question"": ""你是否感到自己对他人没有价值或自责？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 8,
        ""question"": ""你是否感到生活没有意义或目标？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 9,
        ""question"": ""你是否经常感到难以入睡或早醒？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 10,
        ""question"": ""你是否感到自己难以应对日常的压力？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 11,
        ""question"": ""你是否感到自己对社交活动的兴趣降低？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 12,
        ""question"": ""你是否感到自己对食物或体重有显著的变化？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 13,
        ""question"": ""你是否感到自己对过去的经历有强烈的负面情绪？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 14,
        ""question"": ""你是否感到自己难以享受日常生活中的愉悦时刻？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    },
    {
        ""id"": 15,
        ""question"": ""你是否感到自己对未来充满希望或期待？"",
        ""options"": [
            {""value"": 1, ""label"": ""完全不符合""},
            {""value"": 2, ""label"": ""稍微不符合""},
            {""value"": 3, ""label"": ""一般""},
            {""value"": 4, ""label"": ""稍微符合""},
            {""value"": 5, ""label"": ""完全符合""}
        ],
        ""score"": 5
    }
]";
        var questions = JsonSerializer.Deserialize<List<PsychologicalQuestion>>(jsonResponse);
        MentalHealthSelfAssessment model = new MentalHealthSelfAssessment
        {
            PsychologicalDescription = request.UserDescription,
            PsychologicalQuestionsPrompt = prompt,
            PsychologicalQuestions = jsonResponse
        };
        await _mentalHealthSelfAssessmentRepository.InsertAsync(model);
        return new PsychologicalQuestions { MentalHealthSelfAssessmentId = model.Id, PsychologicalQuestion = questions };
    }

    public async Task<AnalysisResult> AnalyzeAnswersAsync(TestAnswerRequest request, CancellationToken cancellationToken = default)
    {
        var totalScore = request.Answers.Sum(a => a.score);
        var averageScore = (double)totalScore / request.Answers.Count;
        var answerQuestions = JsonSerializer.Serialize(request.Answers);

        var prompt = $@"分析用户的心理测试结果并给出专业的建议。信息如下：
1. 用户描述以：{request.UserDescription}；完成测试题结果{answerQuestions}
2. 测试题数量：{request.Answers.Count}题
3. 总分：{totalScore}分
4. 平均分：{averageScore:F2}分

请提供：
1. 详细的心理状况分析
2. 具体的改善建议
3. 风险等级评估（低风险/中等风险/高风险）

请用JSON格式返回，包含analysis（分析）、suggestion（建议）和riskLevel（风险等级）字段。";

        var generateRequest = new GenerateRequest()
        {
            Model = "qwen:14b",
            Format = "json",
            Prompt = prompt
        };

        //var responseBuilder = new StringBuilder();
        //await foreach (var response in _ollama.GenerateAsync(generateRequest, cancellationToken))
        //{
        //    if (response?.Response != null)
        //    {
        //        responseBuilder.Append(response.Response);
        //    }
        //}
        //// 去除最外层的花括号（如果有的话）
        //var jsonResponse = responseBuilder.ToString();
        //if (jsonResponse.StartsWith("{") && jsonResponse.EndsWith("}"))
        //{
        //    jsonResponse = jsonResponse.Replace("{{", "{").Replace("}}", "}");
        //}
        var jsonResponse = @"{
  ""analysis"": ""根据用户完成的心理测试结果，所有15个问题均选择了最高分（5分），表明其在多个心理维度上存在显著困扰。主要表现为：\n\n1. **情绪低落与抑郁倾向**：情绪持续低落、对曾经感兴趣的事物失去兴趣、生活缺乏意义感。\n2. **焦虑症状明显**：频繁感到紧张、难以集中注意力、无法应对日常压力。\n3. **自我评价下降**：自责、认为自己没有价值、对未来感到绝望。\n4. **行为与生理影响**：精力减退、睡眠障碍、食欲/体重变化、社交活动减少。\n5. **正向情绪缺失**：无法从生活中获得愉悦体验，对未来缺乏希望。\n\n综合来看，用户的抑郁和焦虑症状已达到较高程度，可能正在经历中度至重度的抑郁症或共病焦虑症，且已对其日常生活功能造成显著影响。"",
  ""suggestion"": ""1. **立即寻求专业帮助**：建议尽快联系心理咨询师或精神科医生进行正式评估，考虑是否需要药物干预。\n2. **心理治疗推荐**：\n   - 认知行为疗法（CBT）：识别并调整负面思维模式。\n   - 正念训练：增强当下觉察力，缓解焦虑。\n   - 行为激活：逐步恢复日常活动参与，提升动力。\n3. **生活方式调整**：\n   - 保持规律作息，改善睡眠质量。\n   - 增加适度运动，促进内啡肽分泌。\n   - 保证营养均衡饮食，避免高糖高脂食物。\n4. **建立支持系统**：与亲友沟通情绪，避免孤立。\n5. **情绪监测工具使用**：如Daylio、Moodnotes等App记录每日情绪波动。\n6. **紧急情况处理**：若出现自杀念头或计划，请立即联系亲友或拨打心理援助热线。"",
  ""riskLevel"": ""high""
}";
        var mentalHealthSelfAssessment = await _mentalHealthSelfAssessmentRepository.GetByIdAsync(request.MentalHealthSelfAssessmentId);
        ExceptionHelper.ThrowIfNull(mentalHealthSelfAssessment, "数据不存在");

        await _mentalHealthSelfAssessmentRepository.UpdateAsync(x =>
            x.SetProperty(p => p.AnswerQuestions, answerQuestions)
             .SetProperty(p => p.AnalyzeAnswerQuestionsPrompt, prompt)
             .SetProperty(p => p.AnalysisResult, jsonResponse), w => w.Id == request.MentalHealthSelfAssessmentId);

        return JsonSerializer.Deserialize<AnalysisResult>(jsonResponse);
    }

    public async Task DeleteAsync(long id) 
    {
       await _mentalHealthSelfAssessmentRepository.DeleteAsync(x => x.Id == id);
    }
}
